package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.conmon.MyPageData;
import com.woniuxy.mapper.DepartmentMapper;
import com.woniuxy.mapper.DiseaseMapper;
import com.woniuxy.mapper.DoctorMapper;
import com.woniuxy.pojo.Department;
import com.woniuxy.pojo.Disease;
import com.woniuxy.pojo.Result;
import com.woniuxy.pojo.dto.DiseaseDTO;
import com.woniuxy.service.DiseaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author admin
 * @description 针对表【disease(疾病信息表)】的数据库操作Service实现
 * @createDate 2025-06-05 14:50:52
 */
@Service
public class DiseaseServiceImpl extends ServiceImpl<DiseaseMapper, Disease>
        implements DiseaseService {
    @Autowired
    private DiseaseMapper diseaseMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public MyPageData getDisease(Integer pageNum, Integer pageSize) {
        // 1. 构建分页查询条件
        Page<Disease> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件（只查询需要的字段）
        QueryWrapper<Disease> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                "id",           // 用于复选框选择（对应图片中的复选框列）
                "name",         // 对应"疾病"列
                "department_id",// 用于关联科室名称
                "description"   // 对应"疾病描述"列
        );

        // 3. 执行分页查询
        Page<Disease> diseasePage = diseaseMapper.selectPage(page, queryWrapper);
        List<Disease> diseases = diseasePage.getRecords();

        // 4. 处理科室信息（构建"一级科室>二级科室"格式）
        diseases.forEach(disease -> {
            if (disease.getDepartmentId() != null) {
                Department department = departmentMapper.selectById(disease.getDepartmentId());
                if (department != null) {
                    // 获取父科室名称
                    if (department.getParentId() != null && department.getParentId() > 0) {
                        Department parentDept = departmentMapper.selectById(department.getParentId());
                        disease.setDepartmentName(parentDept.getName() + ">" + department.getName());
                    } else {
                        disease.setDepartmentName(department.getName());
                    }
                }
            }
        });

        // 5. 封装分页结果
        return new MyPageData(diseasePage.getTotal(), diseases);
    }

    @Override
    public List<Department> getDiseaseByDepartmentId() {
        // 1. 构建查询条件
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();

        // 2. 只查询数据库实际存在的字段
        queryWrapper.select(
                "id",           // 科室ID
                "name",         // 科室名称
                "parent_id"     // 父科室ID
        );

        // 3. 执行查询
        List<Department> departments = departmentMapper.selectList(queryWrapper);

        // 4. 构建科室层级关系（不依赖数据库字段）
        Map<Integer, Department> departmentMap = new HashMap<>();
        departments.forEach(dept -> departmentMap.put(dept.getId(), dept));

        // 5. 处理层级关系（构建"一级科室>二级科室"格式）
        List<Department> result = new ArrayList<>();
        departments.forEach(dept -> {
            Department department = new Department();
            department.setId(dept.getId());
            department.setName(dept.getName());
            department.setParentId(dept.getParentId());

            // 构建完整科室路径
            if (dept.getParentId() != null && dept.getParentId() > 0) {
                Department parent = departmentMap.get(dept.getParentId());
                if (parent != null) {
                    department.setName(parent.getName() + ">" + dept.getName());
                }
            }
            result.add(department);
        });

        return result;
    }

    @Override
    public Disease getDisease1(Integer id) {
        if (id == null) {
            return null;
        }

        // 1. 直接通过ID查询疾病
        Disease disease = diseaseMapper.selectById(id);
        if (disease == null) {
            return null;
        }

        // 2. 处理科室信息（与图片中的"皮肤性病科>皮肤科"格式一致）
        if (disease.getDepartmentId() != null) {
            Department department = departmentMapper.selectById(disease.getDepartmentId());
            if (department != null) {
                // 构建"一级科室>二级科室"格式
                if (department.getParentId() != null && department.getParentId() > 0) {
                    Department parentDept = departmentMapper.selectById(department.getParentId());
                    disease.setDepartmentName(parentDept.getName() + ">" + department.getName());
                } else {
                    disease.setDepartmentName(department.getName());
                }
            }
        }

        return disease;
    }

    @Override
    public Result createDisease(DiseaseDTO dto) {
        // 1. 参数校验
        if (StringUtils.isBlank(dto.getName())) {
            return Result.fail("疾病名称不能为空");
        }
        if (dto.getDepartmentId() == null) {
            return Result.fail("请选择科室");
        }

        // 2. 验证科室是否存在
        Department department = departmentMapper.selectById(dto.getDepartmentId());
        if (department == null) {
            return Result.fail("选择的科室不存在");
        }

        // 3. 构建实体
        Disease disease = new Disease();
        disease.setName(dto.getName());
        disease.setDescription(dto.getDescription());
        disease.setDepartmentId(dto.getDepartmentId());

        // 4. 保存到数据库
        int inserted = diseaseMapper.insert(disease);
        if (inserted <= 0) {
            return Result.fail("添加疾病失败");
        }

        return Result.ok("添加成功");
    }

    @Override
    public Result updateDisease(DiseaseDTO dto) {
        // 1. 参数校验
        if (dto.getId() == null) {
            return Result.fail("疾病ID不能为空");
        }
        if (StringUtils.isBlank(dto.getName())) {
            return Result.fail("疾病名称不能为空");
        }

        // 2. 检查疾病是否存在
        Disease existing = diseaseMapper.selectById(dto.getId());
        if (existing == null) {
            return Result.fail("疾病不存在");
        }

        // 3. 更新字段
        Disease updateEntity = new Disease();
        updateEntity.setId(dto.getId());
        updateEntity.setName(dto.getName());
        updateEntity.setDescription(dto.getDescription());

        // 4. 如果修改了科室
        if (dto.getDepartmentId() != null
                && !dto.getDepartmentId().equals(existing.getDepartmentId())) {
            Department dept = departmentMapper.selectById(dto.getDepartmentId());
            if (dept == null) {
                return Result.fail("选择的科室不存在");
            }
            updateEntity.setDepartmentId(dto.getDepartmentId());
        }

        // 5. 执行更新
        int updated = diseaseMapper.updateById(updateEntity);
        if (updated <= 0) {
            return Result.fail("更新疾病失败");
        }

        return Result.ok("更新成功");
    }

    @Override
    public MyPageData searchDisease(Integer pageNum, Integer pageSize, Disease disease) {
        // 1. 构建分页对象
        Page<Disease> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        QueryWrapper<Disease> queryWrapper = new QueryWrapper<>();

        // 3. 添加条件判断（根据前端传入的查询条件）
        if (StringUtils.isNotBlank(disease.getName())) {
            // 疾病名称模糊查询
            queryWrapper.like("name", disease.getName());
        }

        if (disease.getDepartmentId() != null) {
            // 按科室ID精确查询
            queryWrapper.eq("department_id", disease.getDepartmentId());
        }

        if (StringUtils.isNotBlank(disease.getDescription())) {
            // 疾病描述模糊查询
            queryWrapper.like("description", disease.getDescription());
        }

        // 4. 执行分页查询
        Page<Disease> diseasePage = diseaseMapper.selectPage(page, queryWrapper);
        List<Disease> diseases = diseasePage.getRecords();

        // 5. 处理科室信息（构建"一级科室>二级科室"格式）
        diseases.forEach(item -> {
            if (item.getDepartmentId() != null) {
                Department department = departmentMapper.selectById(item.getDepartmentId());
                if (department != null) {
                    // 获取父科室名称
                    if (department.getParentId() != null && department.getParentId() > 0) {
                        Department parentDept = departmentMapper.selectById(department.getParentId());
                        item.setDepartmentName(parentDept.getName() + ">" + department.getName());
                    } else {
                        item.setDepartmentName(department.getName());
                    }
                }
            }
        });

        // 6. 封装分页结果
        return new MyPageData(diseasePage.getTotal(), diseases);
    }
}




